package com.yicong.ants.ui.circle.ad;

import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.ImageLoader;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.UrlUtil;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.circle.AdItem;
import com.yicong.ants.databinding.CircleAdEditActivityBinding;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.manager.loader.GlideEngine2;
import com.yicong.ants.ui.circle.home.StaticHtmlEditActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cch
 * @version 2020/8/22
 */
public class AdEditActivity extends BaseTitleBarActivity<CircleAdEditActivityBinding> implements View.OnClickListener {
    AdItem mAdItem;
    Drawable mSelectBg = UiHelper.getDrawable(R.drawable.theme_button_bg);
    Drawable mUnSelectBg = UiHelper.getDrawable(R.drawable.button_edge_ccc);
    int mStyle = 0;

    @Override
    protected int getLayout() {
        return R.layout.circle_ad_edit_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText("修改社区广告");
        mDataBind.setClick(this);
        mAdItem = JsonHelper.toObject(getIntent().getStringExtra(Constants.Extra.JSON), AdItem.class);
        onLoadData();
        initViews();
    }

    private void initViews() {
        mDataBind.title.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mDataBind.titleTextLimit.setText(s.toString().length() + "/64");
            }
        });
        mDataBind.link.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringHelper.isEmpty(s.toString())) {
                    return;
                }
                if (s.toString().contains("api/v2/web/htmlRender?id=")) {
                    mDataBind.createHtml.setText("修改链接内容");
                } else {
                    mDataBind.createHtml.setText("没有链接?创建图文");
                }
            }
        });

        mDataBind.title.setText(mAdItem.getTitle());
        mDataBind.link.setText(mAdItem.getLink());
        if (mAdItem.getLink().contains("api/v2/web/htmlRender?id=")) {
            mDataBind.createHtml.setText("修改链接内容");
        }
        // style
        mStyle = mAdItem.getStyle();
        mDataBind.style0.setBackground(mStyle == 0 ? mSelectBg : mUnSelectBg);
        mDataBind.style1.setBackground(mStyle == 1 ? mSelectBg : mUnSelectBg);

        // image
        ImageLoader.loadImage(mDataBind.imageUpload, mAdItem.getImg_url(), R.drawable.place_holder);
        UiHelper.setVisibleElseGone(mDataBind.imageUploadField, true);
        UiHelper.setVisibleElseGone(mDataBind.imageAdd, false);
        mDataBind.imageUpload.setTag(mAdItem.getImg_url());
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Circle_Ad_Html_Suc:
                mDataBind.link.setText(StaticHtmlEditActivity.mHtmlLink);
                mDataBind.createHtml.setText("修改链接内容");
                break;
        }
    }

    @Override
    protected void onLoadData() {

    }

    void chooseStyle(int style) {
        mDataBind.style0.setBackground(style == 0 ? mSelectBg : mUnSelectBg);
        mDataBind.style1.setBackground(style == 1 ? mSelectBg : mUnSelectBg);
        mStyle = style;
    }

    public void uploadImage(String uri) {
        ImageHelper.uploadImage(mDisposable, uri, respBean -> {
            if (respBean.isCodeFail()) {
                showError();
                return;
            }
            ImageLoader.loadImage(mDataBind.imageUpload, respBean.getData(), R.drawable.place_holder);
            UiHelper.setVisibleElseGone(mDataBind.imageUploadField, true);
            UiHelper.setVisibleElseGone(mDataBind.imageAdd, false);
            mDataBind.imageUpload.setTag(respBean.getData());
        }, throwable -> {
            showError();
            Logs.logException(throwable);
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBackPressed();
                break;
            case R.id.style_0:
                chooseStyle(0);
                break;
            case R.id.style_1:
                chooseStyle(1);
                break;
            case R.id.image_add:
                if (mDataBind.imageUpload.getTag() != null) {
                    showToast("您只能添加一张图片");
                    return;
                }
//                ImageHelper.takeImage(mContext, 1);

                PictureSelector.create(this)
                    .openGallery(SelectMimeType.ofImage())
                    .setMaxSelectNum(1)
                    .setImageEngine(GlideEngine2.createGlideEngine())
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            if (CollectionHelper.isEmpty(result)) {
                                return;
                            }
                            // 结果回调
                            uploadImage(result.get(0).getCutPath());
                        }

                        @Override
                        public void onCancel() {
                            // 取消
                        }
                    });

                break;
            case R.id.image_close:
                mDataBind.imageUpload.setTag(null);
                UiHelper.setVisibleElseGone(mDataBind.imageAdd, true);
                UiHelper.setVisibleElseGone(mDataBind.imageUploadField, false);
                break;
            case R.id.create_html:
                try {
                    if (StringHelper.isNotEmpty(mDataBind.link) && mDataBind.link.getText().toString().contains("api/v2/web/htmlRender?id=")) {
                        String htmlId = UrlUtil.getValueFromUrl(mDataBind.link.getText().toString(), "id");
                        Router.turnTo(mContext, StaticHtmlEditActivity.class)
                            .putExtra(Constants.Extra.Id, htmlId)
                            .start();
                        return;
                    }
                } catch (Exception exception) {
                    showToast(exception.getMessage());
                }
                Router.turnTo(mContext, StaticHtmlEditActivity.class).start();
                break;
            case R.id.review:
                if (StringHelper.isEmpty(mDataBind.title)) {
                    showToast("请填写标题");
                    return;
                }
                if (mDataBind.imageUpload.getTag() == null) {
                    showToast("请上传图片");
                    return;
                }
                Dialogs.showAdReview(mContext, mStyle, mDataBind.title.getText().toString(), String.valueOf(mDataBind.imageUpload.getTag()), null);
                break;
            case R.id.apply:
                if (StringHelper.isEmpty(mDataBind.title)) {
                    showToast("请填写标题");
                    return;
                }
                if (mDataBind.imageUpload.getTag() == null) {
                    showToast("请上传图片");
                    return;
                }
                if (StringHelper.isEmpty(mDataBind.link)) {
                    showToast("请填写链接");
                    return;
                }
                showProgress();
                Map<String, String> map = new HashMap<>();
                map.put("id", mAdItem.getId());
                map.put("title", mDataBind.title.getText().toString());
                map.put("img_url", mDataBind.imageUpload.getTag().toString());
                map.put("link", mDataBind.link.getText().toString());
                map.put("style", String.valueOf(mStyle));

                addSubscribe(RetrofitHelper.getApis().editAd(map)
                    .compose(RxHelper.toMain())
                    .subscribe(respBean -> {
                        hideProgress();
                        if (respBean.isCodeFail()) {
                            showToast(respBean.getMsg());
                            return;
                        }
                        Dialogs.showTaskSuc(mContext, "修改成功", "您的广告审核通过后将会在社区页展示", () -> {
                            //
                            RxBus.get().postEvent(Constants.Event.Expect_Refresh_Manager_Ad);
                            finish();
                        });
                    }, RxHelper.getHideProgressConsumer(this)));
                break;
        }
    }
}
